package org.example.ch01.service;

import org.apache.ibatis.session.SqlSession;
import org.example.ch01.entity.User;
import org.example.ch01.mapper.UserMapper;
import org.example.ch01.util.MybatisUtils;

import java.util.Map;

/**
 * ClassName: UserService
 * Description:
 *
 * @Author zjl
 * @Create 2025/04/22 10:31
 * @Version 1.0
 */
public class UserService {

    public void saveUser(User user) {
        // 创建SqlSession实例
        SqlSession session = MybatisUtils.getSqlSession();
        try {
            // 创建UserMapper接口的代理对象
            // 这个代理对象会解析并执行mapper映射配置文件中的sql
            UserMapper userMapper = session.getMapper(UserMapper.class);
            // 执行代理对象
            userMapper.save(user);
            // 手动提交事务
            session.commit();
        } catch (RuntimeException e) {
            // 事务回滚
            session.rollback();
        } finally {
            session.close();
        }
    }

    public void saveUser2(Map<String, Object> user) {
        // 创建SqlSession实例
        SqlSession session = MybatisUtils.getSqlSession();
        try {
            // 创建UserMapper接口的代理对象
            // 这个代理对象会解析并执行mapper映射配置文件中的sql
            UserMapper userMapper = session.getMapper(UserMapper.class);
            // 执行代理对象
            userMapper.save2(user);
            // 手动提交事务
            session.commit();
        } catch (RuntimeException e) {
            // 事务回滚
            session.rollback();
        } finally {
            session.close();
        }
    }

    public int delete(Integer id) {
        SqlSession session = MybatisUtils.getSqlSession();
        try {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            userMapper.delete(id);
            session.commit();
        } catch (RuntimeException e) {
            session.rollback();
        } finally {
            session.close();
        }
        return 0;
    }

    public void update(User user) {
        SqlSession session = MybatisUtils.getSqlSession();
        try {
            UserMapper userMapper = session.getMapper(UserMapper.class);
            userMapper.update(user);
            session.commit();
        } catch (RuntimeException e) {
            session.rollback();
        } finally {
            session.close();
        }
    }
}
